package com.daveychu.lingo.model;

import java.io.IOException;
import java.util.logging.Logger;

public class Lingo {

	public static final int NR_OF_TURNS = 6;
	public static final int NR_OF_LETTERS = 5;

	private int turns;
	private int score;
	private int[] points = new int[] { 400, 250, 200, 150, 100, 50 };
	private WordList wordList;
	private Letter[] solution;
	private boolean isGameWon;

	public Lingo() {
		try {
			wordList = new WordList();
		} catch (IOException e) {
			Logger.getAnonymousLogger().warning(e.toString());
		}
	}

	public void startNewGame() {
		solution = wordList.getRandomWord();
		turns = 1;
		isGameWon = false;
	}

	/**
	 * @return an array of Letter's with the appropriate values for
	 *         isPlacedCorrectly and isInSolution;
	 */
	public Letter[] attemptWord(String attemptedWord) {

		boolean isAllCorrect = true;

		char[] attemptedLetters = attemptedWord.toCharArray();
		Letter[] letters = new Letter[NR_OF_LETTERS];
		for (int i = 0; i < attemptedLetters.length; i++) {
			letters[i] = new Letter(attemptedLetters[i]);
		}

		for (int i = 0; i < letters.length; i++) {
			if (solution[i].getLetter() == letters[i].getLetter()) {
				letters[i].setPlacedCorrectly(true);
			} else {
				isAllCorrect = false;
				for (int j = 0; j < solution.length; j++) {
					if (solution[j].getLetter() == letters[i].getLetter()) {
						letters[i].setInSolution(true);
					}
				}
			}
		}

		if (isAllCorrect) {
			score += points[turns - 1];
			isGameWon = true;
		}

		return letters;
	}

	public String getLetterHints(String prefix) {
		return wordList.getPossibleNextLetters(prefix);
	}

	public boolean isTurnOver() {
		if (turns > NR_OF_TURNS) {
			return true;
		}
		return false;
	}

	public int getTurns() {
		return turns;
	}

	public void setTurns(int turns) {
		this.turns = turns;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public boolean isWon() {
		return isGameWon;
	}

	public String getSolution() {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < solution.length; i++) {
			sb.append(solution[i].getLetter());
		}

		return sb.toString();
	}

}
